import { defineComponent, VNode, ref, onMounted, computed } from 'vue'
/* hooks */
import { useRouter, useCurrentInstance } from '@src/modules/intelligentQuality/hooks/index.ts'
/* utils */
import { t } from '@src/locales';
import { Fragment } from 'vue-frag'
import { openAccurateTab } from '@src/util/platform'
import platform from '@src/platform/index.js'
import state from '@src/modules/intelligentQuality/utils/state.ts'
/* type */
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
/* components */
import CreateContent from '@src/modules/intelligentQuality/views/newInfo/components/createContent.tsx'
/* scss */
import '@src/modules/intelligentQuality/views/newInfo/index.scss'
import '@src/modules/intelligentQuality/views/newInfo/components/index.scss'
/* http */
import * as IntellIgentApi from '@src/api/intelligentQuality.js'
import { message } from '@src/util/message'

export default defineComponent({
    name: 'intelligentRobotNewInfo',
    setup(props) {
        const { query } = useRouter()
        const name = query.name || ''
        const remarks = query.desc || ''
        const isEdit = query.isEdit || false
        const robotNo = query.robotNo || '' // 机器人编号详情
        const buttonDisabled = ref(false)
        const filedObj = ref({
            formId: '',
            fieldList: [],
            examplePicList: [],
            minCheckCount: 1,
            minCheckScore: 50,
            minPictureCheckScore: 50,
            nowCheck: false
        })

        const activeCheck = ref(1)
        const loading = ref(true)
        

        const goDetailTab = (robotNo: string) => {
            const fromId = window?.frameElement?.getAttribute('id') as string
            openAccurateTab({
              type: PageRoutesTypeEnum.IntelligentQualityDetail,
              params: `robotNo=${robotNo}`,
              fromId
            })
        }
        
        const goListTab = () => {
            const fromId = window?.frameElement?.getAttribute('id') as string
            openAccurateTab({
              type: PageRoutesTypeEnum.IntelligentQuality,
              fromId
            })
        }
        
        const closeTab = () => {
            // @ts-ignore
            const id = window.frameElement?.dataset?.id
            platform.closeTab(id)
        }
        
        const refreshFromTab = () => {
            let fromId = window?.frameElement?.getAttribute('fromid')
            platform.refreshTab(fromId)
        }

        /**
         * @description: 保存
         */
        const save = () => {
            buttonDisabled.value = true
            if (isEdit) {
                IntellIgentApi.updateRobot({
                    ...filedObj.value
                }).then(res => {
                    if (!res.success) {
                        message.error(res.message)
                        return
                    }
                    message.success(t('robot.text3'))
                    buttonDisabled.value = false
                    const robotNo = res.data
                    goDetailTab(robotNo)
                    refreshFromTab()
                    closeTab()
                })
                .catch(err => {
                    message.error(err.message)
                    console.error(err)
                    buttonDisabled.value = false
                })
            } else {
                IntellIgentApi.createRobot({
                    name: name,
                    remarks: remarks,
                    ...filedObj.value
                }).then(res => {
                    if (!res.success) {
                        message.error(res.message)
                        return
                    }
                    message.success(t('robot.save1'))
                    buttonDisabled.value = false
                    // goListTab()
                    refreshFromTab()
                    closeTab()
                })
                .catch(err => {
                    message.error(err.message)
                    buttonDisabled.value = false
                    console.error(err)
                })
            }
        }

        const cancelHandler = () => {
            closeTab()
        }

        /**
         * @description 获取机器人详情
         */
        const getDetail = () => {
            IntellIgentApi.getRobotDetail({
                robotNo: robotNo
            }).then(res => {
                if (!res.success) {
                    message.error(res.message)
                    return
                }
                filedObj.value = Object.assign(filedObj.value, res.data)
                initState(filedObj.value)
                loading.value = false
            })
            .catch(err => {
                message.error(err.message)
                console.error(err)
            })
        }

        /**
         * @description 初始化状态数据
         * @param data 
         */
        const initState = (data: any) => {
            if (!data) return
            if (!!data.formId) {
                state.vailFormId = data.formId
            }
            if (data.fieldList && Array.isArray(data.fieldList)) {
                state.vailFieldList = data.fieldList
            }
            if(data.examplePicList && data.examplePicList.length > 0) {
                state.vailPicList = data.examplePicList
            }
        }

        /**
         * @description 设置质检的目标字段
         */
        const settingFieldHandler = () => {
            if (state.vailFormId && state.vailFieldList.length > 0) {
                activeCheck.value = activeCheck.value + 1
                return
            }
            message.warning(t('robot.text4'))
        }

        /**
         * @description 设置质检图片
         */
        const settingPhotoHandler = () => {
            if (state.vailPicList.length > 0) {
                activeCheck.value = activeCheck.value + 1
                return
            }
            message.warning(t('robot.text5'))
        }
        
        const handlerChange = (item: any) => {
            filedObj.value = Object.assign(filedObj.value, item)
        }

        // 存在机器人编号和编辑状态 获取详情编辑状态
        if (robotNo && isEdit) {
            getDetail()
        } else {
            loading.value = false
        }

        return () => (
            <div class="intelligent-views" v-loading={loading.value}>
                {loading.value ? (
                    <div class="loading">{t('robot.loading')}</div> // 显示加载指示器
                ) : (
                    <div class="container">
                        <div class="create-header">
                            <div class="create-header__title">
                                {isEdit ? `${t('robot.edit')}${filedObj.value?.name || t('robot.robotName')}` : t('robot.robotName1')}
                            </div>
                            <div class="create-header__btns">
                                {activeCheck.value === 1 ? (
                                    <Fragment>
                                        <el-button type='plain-third' onClick={() => cancelHandler()}>{t('robot.cancel')}</el-button>
                                        <el-button type="primary" onClick={() => settingFieldHandler()}>{t('robot.next')}</el-button>
                                    </Fragment>
                                ) : activeCheck.value === 2 ? (
                                    <Fragment>
                                        <el-button type='plain-third' onClick={() => cancelHandler()}>{t('robot.cancel')}</el-button>
                                        <el-button type='plain-third' onClick={() => {activeCheck.value = activeCheck.value - 1}}>{t('robot.back')}</el-button>
                                        <el-button type="primary" onClick={() => settingPhotoHandler()}>{t('robot.next')}</el-button>
                                    </Fragment>
                                ) : (
                                    <Fragment>
                                        <el-button type='plain-third' onClick={() => cancelHandler()}>{t('robot.cancel')}</el-button>
                                        <el-button type='plain-third' onClick={() => {activeCheck.value = activeCheck.value - 1}}>{t('robot.back')}</el-button>
                                        <el-button type="primary" onClick={() => save()} disabled={buttonDisabled.value}>{t('robot.save2')}</el-button>
                                    </Fragment>
                                )}
                            </div>
                        </div>
                        <CreateContent activeCheck={activeCheck.value} data={filedObj} onChange={(data) => handlerChange(data)} isEdit={Boolean(isEdit)} />
                    </div>
                )}
            </div>
        ) as unknown as VNode
    }
})